﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BEPUphysics;
using Microsoft.Xna.Framework;
using System.Threading;
using System.Diagnostics;

namespace The_LarX
{
    public class BepuPhysics : Component
    {
        public static BepuPhysics ActualBepuPhysics;

        public Space Space;

        public BepuPhysics(GameScreen Screen)
            : base(Screen)
        {            
            Load();   
        }
        public BepuPhysics()
        {
            Load();
        }

        public override void DisableComponent()
        {
            base.DisableComponent();

            Space.Dispose();
            ActualBepuPhysics = null;
        }

        protected void Load()
        {
            ActualBepuPhysics = this;

            Space = new Space();
            Space.ForceUpdater.Gravity = new Vector3(0, -9.82f, 0);
            
#if XBOX            
            Space.ThreadManager.AddThread(delegate(object information) { Thread.CurrentThread.SetProcessorAffinity(new int[] { 1 }); }, null);
            Space.ThreadManager.AddThread(delegate(object information) { Thread.CurrentThread.SetProcessorAffinity(new int[] { 3 }); }, null);
            Space.ThreadManager.AddThread(delegate(object information) { Thread.CurrentThread.SetProcessorAffinity(new int[] { 5 }); }, null);
#else
#if !WINDOWS_PHONE
            if (Environment.ProcessorCount > 1)
            {
                for (int i = 0; i < Environment.ProcessorCount; i++)
                {
                    Space.ThreadManager.AddThread();
                }
            }
#endif
#endif            
        }

        public override void Update()
        {
            try
            {
                base.Update();

                Space.Update();

                if (!Engine.Services.ContainsService(typeof(BepuPhysics)))
                {
                    Engine.Services.AddService(typeof(BepuPhysics), this);
                }
            }
            catch { }
        }
    }
}
